package com.kai.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CodeUtils {


    private static int width =150;
    private static int height=50;
    private static String codeText="";
    private static String[] strs={"a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z",
            "A","B","C","D","E","F","G","H","J","K","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
            "2","3","4","5","6","7","8","9"};

    /**
     * 获取验证码图片
     * @return
     */
    public static BufferedImage imageCode(){
        int red;
        int blue;
        int green;
        //创建一个画板 ：一张图片
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //获取一个画笔
        Graphics2D g= (Graphics2D) image.getGraphics();
        //设置画笔颜色
        g.setColor(Color.LIGHT_GRAY);
        //填充图片
        g.fillRect(0,0,width,height);


        //从strs数组中获取一个随机数
        Random random = new Random();
        //设置画笔颜色
        //g.setColor(Color.blue);
        //设置字体类型，  加不加粗Font.BOLD(粗体)   ，大小
        g.setFont(new Font("楷体",Font.BOLD,30));
        int x=30,y=35;
        String code="";
        //循环4次
        for (int i = 0; i < 4; i++) {
            //随机获取0-60数字，strs.length长度为61
            int index = random.nextInt(strs.length);
            //下标为index的字符
            String str=strs[index];
            //拼接字符，输出验证码
            code=code + str;
            codeText=code;
            //获取到不同的颜色
            red = random.nextInt(150)+55;
            blue = random.nextInt(150)+55;
            green = random.nextInt(150)+55;
            g.setColor(new Color(red,blue,green));

            //随机获取-45到45 角度从-45到45
            int angle = random.nextInt(91)-45;
            //弧度=角度*pi/180
            double radian = angle * Math.PI /180;
            //调用方法，旋转字符角度
            g.rotate(radian,x,y);
            //把字符写到画布上
            g.drawString(str,x,y);
            //恢复到以前的角度
            g.rotate(-radian,x,y);
            x+=25;
        }
        //画干扰线 10条
        for (int i = 0; i < 2; i++) {

            int x1 = random.nextInt(30);
            int y1 = random.nextInt(27)+3;

            int x2 = random.nextInt(30)+120;
            int y2 = random.nextInt(27)+3;


            red = random.nextInt(255);
            blue = random.nextInt(255);
            green = random.nextInt(255);

            g.setColor(new Color(red,blue,green));

            g.drawLine(x1,y1,x2,y2);

        }
        return image;
    }

    /**
     * 图片上的文本
     * @return
     */
    public static String getCodeText(){
        return codeText;
    }

    public static void main(String[] args) {
        imageCode();
        System.out.println(getCodeText());
    }
}
